package com.xr.sunnyday.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.StringUtil;
import com.xr.sunnyday.dao.SetmealDao;
import com.xr.sunnyday.entity.PageResult;
import com.xr.sunnyday.entity.QueryPageBean;
import com.xr.sunnyday.exception.SunnydayException;
import com.xr.sunnyday.pojo.Setmeal;
import com.xr.sunnyday.service.SetmealService;
import com.xr.sunnyday.utils.QiNiuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImp implements SetmealService{

    @Autowired
    private SetmealDao setmealDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        if (!StringUtil.isEmpty(queryPageBean.getQueryString())){
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        //3.开启查询,Page是分页信息
        Page<Setmeal> page = setmealDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    @Transactional
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer id = setmeal.getId();
        if(null!=checkgroupIds){
            for (Integer ids : checkgroupIds){
                setmealDao.addSetmealCheckgroup(id,ids);
            }
        }

        //第②部分：FreeMarker处理
        // a.新增套餐后需要重新生成静态页面
//        generateMobileStaticHtml();
    }

    /*private void generateMobileStaticHtml() {
        try {
            //1.套餐列表静态页面
            generateSetmealListHtml();
            //2.套餐详情静态页面生成单个就行了，为了测试方便，生成所有的
            generateSetmealDetailHtml();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    //b.1生成套餐静态页面
    private void generateSetmealListHtml() {
        //1.准备模板文件路径,freemarker配置文件中已经配置好了路径前缀
        String templateName = "mobile_setmeal.ftl";
        //2.准备套餐列表页面的数据
        List<Setmeal> setmealList = setmealDao.findAll();
        //2.1.拼图片路径返回
        setmealList.forEach(setmeal -> {
            setmeal.setImg(QiNiuUtils.DOMAIN+setmeal.getImg());
        });
        //3.构建数据
        Map<String,Object> dataMap = new HashMap<String,Object>();
        //注意，key值一定要与模板文件中的变量保持一致
        dataMap.put("setmealList",setmealList);
        //4.输出全路径
        String setmealListFile = out_put_path+"mobile_setmeal.html";
        //调用封装的页面生成方法
        generateHtml(templateName,dataMap,setmealListFile);

    }

    //b.2生成套餐详情静态页面
    private void generateSetmealDetailHtml() {
        //1.准备模板文件路径,freemarker配置文件中已经配置好了路径前缀
        String templateName = "mobile_setmeal_detail.ftl";
        //2.准备数据：把所有套餐都生成详情页面,方便测试
        List<Setmeal> setmealList = setmealDao.findAll();
        //2.1setmealList中的套餐是没有详情信息，即没有检查组也没有检查项的信息，要查询一遍
        for (Setmeal setmeal : setmealList) {
            //2.2.获取套餐详情
            Setmeal setmealDetail = setmealDao.findDetailById(setmeal.getId());
            //2.3设置套餐的图片路径
            setmealDetail.setImg(QiNiuUtils.DOMAIN + setmealDetail.getImg());
            //3.构建数据
            Map<String, Object> dataMap = new HashMap<String,Object>(); dataMap.put("setmeal", setmealDetail);
            //4.输出全路径
            String setmealListFile = out_put_path+"mobile_setmeal_" + setmealDetail.getId() + ".html";
            //调用封装的页面生成方法
            generateHtml(templateName,dataMap,setmealListFile); }
    }*/


    @Override
    public Setmeal findByid(int setmealid) {
        return setmealDao.findByid(setmealid);
    }

    @Override
    public List<Integer> findCheckGroupBySetmel(int setmealid) {
        return setmealDao.findCheckGroupBySetmel(setmealid);
    }

    @Override
    @Transactional
    public void update(Setmeal setmeal, int[] checkgroupIds) {
        setmealDao.update(setmeal);
        setmealDao.deleteCheckSetmelGroup(setmeal.getId());
        if (null!=checkgroupIds){
            for (Integer ids:checkgroupIds){
                setmealDao.addSetmealCheckgroup(setmeal.getId(),ids);
            }
        }
    }

    @Override
    @Transactional
    public void delete(int setmealid) {
        //查他的上一级订单表有没有关系
        int id = setmealDao.findorderBySetmel(setmealid);
        if (id>0){
            throw new SunnydayException("该检查组关联着套餐，不能删除");
        }
        //没有就先解除下一级的关系
        setmealDao.deleteCheckSetmelGroup(setmealid);
        //最后删除自己
        setmealDao.delete(setmealid);
    }

    @Override
    public List<String> findImgs() {
        return setmealDao.findImgs();
    }

    @Override
    public Setmeal findDetailById(int id) {
        return setmealDao.findDetailById(id);
    }

    @Override
    public List<Setmeal> findAll() {
        List<Setmeal> setmealList = setmealDao.findAll();
        //遍历，给集合中的每一个套餐的img属性拼接7牛云的外连接域名
        for (Setmeal setmeal: setmealList) {
            setmeal.setImg(QiNiuUtils.DOMAIN+setmeal.getImg());
            System.out.println(setmeal.getImg());
        }
        return setmealList;
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }


//    @Autowired
//    private FreeMarkerConfig freemarkerConfig;
//
//    @Value("${out_put_path}")
//    private String out_put_path;

    /**
     *
     *封装生成静态页面的方法
      */
    /*private void generateHtml(String templateFileName, Map<String,Object> dataMap, String outFileName){
        //1.拿到Configuration对象
        Configuration configuration = freemarkerConfig.getConfiguration();

        //缓冲流,加大读写效率
        BufferedWriter writer= null;
        try {
            //2.加载模板文件-已有
            Template template = configuration.getTemplate(templateFileName);
            //3.准备数据->已有
            //4.输出文件路径
            writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFileName),"utf-8"));
            //5.填充数据
            template.process(dataMap, writer);
            //6.刷流
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }finally {
            try {
                //7.关流
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }*/

}
